#include "times.h"

inline int maketime(const char *s, time_t *ptime)
{
    struct tm tm1;
    int len = strlen(s);
    if (len != 14)
        return -1;
    tm1.tm_year = (s[0] -'0')*1000 + (s[1] -'0')*100 + (s[2]-'0')*10 + (s[3]-'0') - 1900;
    tm1.tm_mon  = (s[4] -'0')*10   + (s[5] -'0') - 1;
    tm1.tm_mday = (s[6] -'0')*10   + (s[7] -'0');
    tm1.tm_hour = (s[8] -'0')*10   + (s[9] -'0');
    tm1.tm_min  = (s[10]-'0')*10   + (s[11]-'0');
    tm1.tm_sec  = (s[12]-'0')*10   + (s[13]-'0');
    *ptime = mktime(&tm1);
    return 0;
}

// stime output format: 20121212111111
inline void times_compact(time_t tim, char *stime, int slen)
{
    struct tm tm1;
    localtime_r(&tim, &tm1);
    strftime(stime, slen, "%Y%m%d%H%M%S", &tm1);
}   
// stime output format: 2012-12-12 11:11:11
inline void times_friendly(time_t tim, char *stime, int slen)
{
    struct tm tm1;
    localtime_r(&tim, &tm1);
    strftime(stime, slen, "%Y-%m-%d %H:%M:%S", &tm1);
}
// stime output format: 2012-12-12-3 11:11:11
inline void times_friendly_week(time_t tim, char *stime, int slen)
{
    struct tm tm1;
    localtime_r(&tim, &tm1);
    strftime(stime, slen, "%Y-%m-%d-%w %H:%M:%S", &tm1);
}
// stime output format: Wed Dec 12 11:11:11 2012
inline void times_friendly_english(time_t tim, char *stime, int slen)
{
    snprintf(stime, slen, "%s", ctime(&tim));
    if (strrchr(stime, '\n')) 
        *strrchr(stime, '\n') = 0;
}
inline char * fmt_time(time_t t, char *p, size_t len, void (*cbtime)(time_t, char*, int))
{
    cbtime(t, p, len);
    return p;
}
inline char * fmt_time_now(char *p, size_t len, void (*cbtime)(time_t, char*, int))
{
    time_t now = time(0);
    cbtime(now, p, len);
    return p;
}
